<?php
namespace Common\Model;
use Think\Model;
class FileModel extends Model {
    public function upload($dir) {
        $upload = new \Think\Upload();

        $upload->exts =  array('jpg', 'gif', 'png', 'jpeg', 'xls', 'zip');
        $upload->rootPath = './Uploads/'.$dir.'/';
        $upload->saveName = time().'_'.mt_rand();
        $info = $upload->upload();

        if(!$info) {
            echo $upload->getError();
        }else{
            $pic_url = $info[$dir]['savepath'].$info[$dir]['savename'];
            return "$dir/".$pic_url;
        }
    }

    /**
     * @param $dir
     * @param $ext
     * @return array
     */
    public function upload2($dir,$ext) {
        $new_dir = './Uploads/'.$dir.'/';
        $upload = new \Think\Upload();
        $upload->exts =  $ext;
        $upload->rootPath = $new_dir;

        if(!is_dir($new_dir)){
            mkdir($new_dir ,0777 ,true);
        }

        $upload->saveName = time().'_'.mt_rand();
        $info = $upload->upload();

        if(!$info) {
            $data = array(
                'state' => 'error',
                'info' => $upload->getError()
            );
        }else{
            $pic_url = $info['csv']['savepath'].$info['csv']['savename'];
            $data = array(
                'state'=>'success',
                'dir'=>"$dir/".$pic_url
            );
        }
        return $data;
    }



    public function upload3($dir) {
        $new_dir = './Uploads/'.$dir.'/';
        $upload = new \Think\Upload();
        $upload->exts =  array('zip');
        $upload->rootPath = $new_dir;

        if(!is_dir($new_dir)){
            mkdir($new_dir ,0777 ,true);
        }
        $upload->saveName = time().'_'.mt_rand();
        $info = $upload->upload();
        if (!$info) {
            return $upload->getError();
        } else {
            return $info;
        }

    }

    /**
     * 返回压缩包里面的目录名
     * $zip_url:压缩包路径,必传
     * $zip_catalog:返回的压缩包目录名的数组
     */
    public function packageCatalog($zip_url,$zip_catalog = array()) {
        $resource = zip_open($zip_url);
        while ($dir_resource = zip_read($resource)) {//读取压缩包
            $name = zip_entry_name($dir_resource);//压缩包的目录和文件的名称
            $end = substr($name, -1);
            if ($end == '/') {//如果是已/结尾,说明是目录,否则是文件
                $good_id = substr($name,0,strlen($name)-1);
                array_push($zip_catalog, $good_id);
            }
        }
        return $zip_catalog;
    }












}

